package com.solidtrust.app.controller;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.solidtrust.app.SolidtrustConstants;
import com.solidtrust.common.FreePersister;
import com.solidtrust.entity.AccessItem;
import com.solidtrust.entity.Area;
import com.solidtrust.entity.CarImage;
import com.solidtrust.entity.Model;
import com.solidtrust.repository.AreaRepository;
import com.solidtrust.repository.GanjiRepository;
import com.solidtrust.repository.ModelRepository;
import com.solidtrust.repository.VolumeRepository;
import com.solidtrust.util.DateUtil;


@RestController
@RequestMapping("api")
public class APIController {

	private static final Logger log4j = Logger.getLogger(APIController.class);
	private static final Integer MAX_MILEAGE = 9999999;
	private static final Integer _5000 = 5000;
	private static final Float LEFT_RATE = 0.6f;
	private static final Float RIGHT_RATE = 1.5f;
	
	@Autowired FreePersister free;
	@Autowired GanjiRepository ganjiRep;
	@Autowired AreaRepository areaRep;
	@Autowired VolumeRepository volRep;
	@Autowired ModelRepository modelRep;
	
	
	@ModelAttribute("access")
	public AccessItem initAccessItem(HttpServletRequest request){
		AccessItem ai = new AccessItem();
		ai.setIp(request.getRemoteHost());
		ai.setUsername(request.getAttribute(SolidtrustConstants.CLIENT_ID) + "");
		request.setAttribute("access", ai);
		return ai;
	}
	
	@ExceptionHandler(Exception.class)
    public String exceptionHandler(Exception ex, HttpServletRequest request){    
       log4j.error(ex.getMessage(), ex);
       AccessItem access = (AccessItem) request.getAttribute("access");
       access.setStatus(-1);
       return "error";
    }
	
	/**
	 * Ganji sold price see PriceController2.java
	 * @param area
	 * @param brand
	 * @param model
	 * @param build
	 * @param volume
	 * @param mileage km
	 * @return
	 */
	
	@RequestMapping("price")
	public Object[] ganjiPrice(@RequestParam(value="area", required = false) Integer area,
			@RequestParam(value="brand") Integer brand,
			@RequestParam(value="model") Integer model,
			@RequestParam(value="build") String build,
			@RequestParam(value="volume", required = false) Integer volume,
			@RequestParam(value="mileage") Integer mileage,
			@ModelAttribute("access") AccessItem access){
		
		Date from = DateUtils.addMonths(new Date(), -4);
		
		//mileage
		int start = 0, end = MAX_MILEAGE;
		if(mileage != null){
			if(mileage < _5000){
				end = _5000;
			}else{
				start = (int)(mileage * LEFT_RATE);
				end = (int)(mileage * RIGHT_RATE);
			}
		}
		
		Model m = modelRep.findOne(model);
		String p2 = m.getBrand().getBrand(),
				p3 = m.getModel(),
				p4 = build;
		Integer averageByCity = 0, averageByProvince = 0, average = 0;
		if(area != null && area != 0){
			Area c = areaRep.findOne(area);
			List<String> cities = areaRep.getCitiesInSameProvince(area);
			
			String p1 = c.getNameOfGanji();
					
			access.setRequest(MessageFormat
						.format("city={0},brand={1},model={2},build={3},volume={4},datefrom={5},mileage={6}-{7}",
								p1, p2, p3, p4, volume, DateUtil.date2String2(from), start, end));
			
			if(volume != null && volume != 0){
				averageByCity = ganjiRep.averageByCity(p1, p2, p3, p4, 
							volume, from, start, end);
				averageByProvince = ganjiRep.averageByCities(cities, p2, p3, p4, 
						volume, from, start, end);
			}else{
				averageByCity = ganjiRep.averageByCity1(p1, p2, p3, p4, 
						from, start, end);
				averageByProvince = ganjiRep.averageByCities1(cities, p2, p3, p4, 
					from, start, end);
			}
		}
		if(volume != null && volume != 0){
			average = ganjiRep.average(p2, p3, p4, volume, from, start, end);
		}else{
			average = ganjiRep.average1(p2, p3, p4, from, start, end);
		}
		if(average != null){
			access.setResponse(averageByCity + "," + averageByProvince + "," + average);
		}else{
			access.setStatus(0);
		}
		free.save(access);
		return new Object[]{averageByCity, averageByProvince, average};
	}
	
	@RequestMapping("images")
	public String image(@RequestParam(value="model") Integer model,
			@ModelAttribute("access") AccessItem access){
		Model m = modelRep.findOne(model);
		access.setRequest(m.getModel());
		CarImage image = m.getImage();
		if(image != null && image.getImage1() != null){
			access.setResponse(image.getImage1());
			return SolidtrustConstants.IMAGE_PREFIX + image.getImage1();
		}
		access.setStatus(0);
		free.save(access);
		return null;
	}
			
}
